package com.ruohi.manage;

import java.io.IOException;
import java.sql.Connection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ruohi.util.common.CommonString;
import com.ruohi.util.common.UTF8PostMethod;
import com.ruohi.util.dbutil.DBHelper;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;


public class Tools {
	public static void loadStaticVariable() {
		
	}
	
	@SuppressWarnings( { "unchecked", "static-access" })
	public static String getNo(String parNo, String table, String enumNo) {
		String no = "";
		Connection conn = null;
		DBHelper dbHelper = DBHelper.getInstance();
		String sql = "";
		try {
			conn = PoolManager.getConnection(DBType.getDBTypeByEnum(enumNo));
			sql = " SELECT no AS no FROM " + table + " ";
			sql += " WHERE no  IS NOT NULL AND isnumeric(no) = 1 ";
			sql += " AND parent_no = ? ";
			sql += "ORDER BY no";
			List list = dbHelper.getMapList(sql, new Object[] { parNo }, conn);
			long intNo = (long) 0;
			if (null != list && list.size() > 0) {
				String intNoStr = (String)(((Map) list.get(list.size() - 1)).get("no"));
				intNo = Long.parseLong( (String) ((Map) list.get(list.size() - 1)).get("no"));
				intNo++;
				no = intNo + "";
				no = intNoStr.substring(0, (intNoStr.length()-no.length()))+intNo;
			} else if (parNo.equals("0")) {
				intNo = (long) 101;
				no = intNo + "";
			} else {
				no = parNo + "001";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dbHelper.freeConnection(conn);
		}
		return no;
	}
	
	/**
	 * 获得最大的编号+1
	 * @param table 表名
	 * @param enumNo 数据源编号
	 * @param c 编号包括字母位数
	 * @return
	 */
	@SuppressWarnings( { "unchecked", "static-access" })
	public static String getNo(String table, String enumNo, int c) {
		String no = "";
		Connection conn = null;
		DBHelper dbHelper = DBHelper.getInstance();
		String sql = "";
		try {
			conn = PoolManager.getConnection(DBType.getDBTypeByEnum(enumNo));
			sql = " SELECT top 1 no FROM " + table + " ";
			sql += "ORDER BY no desc";
			Map m = dbHelper.getMap(sql, conn);
			Integer intNo = 0;
			if (null != m && m.get("no")!=null) {
				intNo = Integer.parseInt(m.get("no").toString().substring(c));
				intNo++;
				no = intNo + "";
			} else {
				no ="100001";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dbHelper.freeConnection(conn);
		}
		return no;
	}
	/**
	 * 递归获得类型参数：当前类别没有参数，获得上级类别的参数，直到有参数为止
	 * @param category
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<Map> getCategoryParam(String category, String enumNo){
		Connection conn = null;
		DBHelper dbHelper = DBHelper.getInstance();
		String sql = "select * from gift_category_param where parent_no = '"+category+"' and is_show = 1 order by order_no desc,no asc";
		List list = null;
		try {
			conn = PoolManager.getConnection(DBType.getDBTypeByEnum(enumNo));
			list = dbHelper.getMapList(sql,conn);
			if((list ==null || list.size()<=0)&&category.length()>=6){
				list = getCategoryParam(category.substring(0,category.length()-3),enumNo);
			}
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.freeConnection(conn);
		}
		return list;
	}
	
	// 获取当前月有多少天
	public   static   int   getMonthDays(String YYYYMM)   throws   ParseException{  
		   String strDate = YYYYMM;
		   SimpleDateFormat   sdf   =   new   SimpleDateFormat("yyyyMM");
		   Calendar   calendar   =   new   GregorianCalendar();  
		   Date date = null ;;
		try {
			date = sdf.parse(strDate);
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		}
		   calendar.setTime(date);  
		   int   day   =   calendar.getActualMaximum(Calendar.DAY_OF_MONTH);  
		   return day;
		}
	/**
	 * 根据父节点递归获取孩子树形
	 * @param parNo：父节点值
	 * @param list：List集合
	 * @param parentField：父节点字段名
	 * @param field：子节点字段名
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<Map> getTreeByPno(String parNo, List<Map> list , String parentField ,String field) {
		List<Map> rList = new ArrayList<Map>(0);
		String parentValue = "";
		String value = "";
		if(list !=null && list.size() > 0){
			for (Map m : list) {
				parentValue = m.get(parentField).toString();
				value = m.get(field).toString();
				if (parentValue.equals(parNo)) {
					rList.add(m);
					List <Map> childList = getTreeByPno(value,list,parentField,field);
					rList.addAll(childList);
				}
			}
		}
		return rList;
	}
	/**
	 * 根据字符长度获取空格
	 * 
	 * @param str
	 *            字符串
	 * @return Html的空格
	 */
	public static String getSpace(String str,int multiple) {
		StringBuffer sb = new StringBuffer();
		if (null != str) {
			for (int i = 0; i < str.length()*multiple; i++) {
				sb.append("&nbsp;");
			}
		}
		return sb.toString();
	}

	public static String UTF8ToGB(String strValue) {
	if (strValue == null || strValue.trim().length() == 0) {
	return null;
	}
	StringBuffer strbuf = new StringBuffer();
	String[] strarr = strValue.split(";");
	int il = strarr.length;
	for (int i = 0; i < il; i++) {
	int pos = strarr[i].indexOf("&#");
	if (pos >= 0) {
	if (pos > 0) {
	strbuf.append(strarr[i].substring(0, pos));
	}

	String tmp = strarr[i].substring(pos + 2);
	if (tmp.startsWith("00")) {
	tmp = tmp.substring(2);
	}

	try {
	int l = Integer.valueOf(tmp);
	if ((l > 10000) || (l < 1000)) {
	strbuf.append((char) l);
	} else {
	strbuf.append("&#").append(tmp).append(";");
	}
	} catch (NumberFormatException e) {
	strbuf.append(tmp);
	}
	} else {
	strbuf.append(strarr[i]);
	}
	}
	return strbuf.toString();
	}

	/**
	 * 返回数字格式
	 * @param source
	 * @param places 小数的位数
	 * @return
	 */
	public static String getFormatDecimal(double source, int places){
		String formatStr = "#0";
		if (places > 0) {
			formatStr += ".";
			
			for (int i = 1; i <= places; i++) {
				formatStr += "0";
			}
		}
		return new DecimalFormat(formatStr).format(source);
	}
	
	public static void main(String []args) throws JSONException{	
		JSONArray arr = new JSONArray("[{'no':'112','name':'材质','param':[{'no':'112002','name':'塑料'},{'no':'112003','name':'合金'}]},{'no':'119','name':'比例','param':[{'no':'119002','name':'1:25'}]}]");
		JSONObject o = null;
		JSONArray subArr = null;
		JSONObject subO = null;
		for(int i = 0;i < arr.length();i++){
			o = arr.getJSONObject(i);
			System.out.println("parent="+o.get("no")+"="+o.get("name"));
			System.out.println("param="+o.get("param"));
			subArr = new JSONArray(o.get("param").toString());
			for(int j= 0; subArr != null && j< subArr.length();j++){
				subO = subArr.getJSONObject(j);
				System.out.println("sub="+subO.get("no")+"="+subO.get("name"));
			}
		}
	}
	/**
	 * 执行图片删除POST请求
	 * 
	 * @param url
	 *            要请求的地址
	 * @param params
	 *            参数
	 * @return 返回请求地址结果
	 * @throws HttpException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static String doImagesPost(String url, List<Map> params) throws Exception, IOException {
		HttpClient httpClient = new HttpClient();
		String result = "fail";
		PostMethod postMethod = new UTF8PostMethod(url);
		
		if (null != params && params.size() > 0) {
			Object value = null;
			NameValuePair [] nameValue = new NameValuePair[params.size()];
			int k = 0;
			NameValuePair n = null;
			for(Map m:params){
				n = new NameValuePair();
				value = m.get("img1");
				n.setName("imgFiles");
	            n.setValue((String)value);
	            nameValue[k]=n;
	            if (null == value) {
					continue;
				}
				k++;
			}
			postMethod.addParameters(nameValue);
		}
		int statusCode = httpClient.executeMethod(postMethod);
		//int statusCode = 0;
		if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
			result = "ok";
		}
		result = new String(postMethod.getResponseBody(), "UTF-8");
		return result;
	}
}
